package com.dingding.service.userorderservice.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.baseservice.payment.wechat.WechatPayApi;
import com.dingding.bean.api.wechat.SecondSign;
import com.dingding.bean.api.wechat.WechatPayOrderQueryResponse;
import com.dingding.bean.api.wechat.WechatPayOrderResponse;
import com.dingding.bean.api.wechat.WechatPayResult;
import com.dingding.bean.databean.push.PushAutomaticCancelOrder;
import com.dingding.bean.databean.push.PushCancelOrder;
import com.dingding.bean.databean.push.PushCompetitiveOrder;
import com.dingding.bean.databean.push.PushConfirmArrival;
import com.dingding.bean.databean.push.PushData;
import com.dingding.bean.databean.push.PushPassengerPay;
import com.dingding.bean.databean.request.ReqCancelOrder;
import com.dingding.bean.databean.request.ReqConfirmArrival;
import com.dingding.bean.databean.request.ReqGetLastUserOrder;
import com.dingding.bean.databean.request.ReqGetOrderInfo;
import com.dingding.bean.databean.request.ReqGetUserOrder;
import com.dingding.bean.databean.request.ReqPassengerPay;
import com.dingding.bean.databean.request.ReqPayOrder;
import com.dingding.bean.databean.request.ReqQueryOrderResult;
import com.dingding.bean.databean.response.DataResponse;
import com.dingding.bean.databean.response.ResGetLastUserOrder;
import com.dingding.bean.databean.response.ResGetOrderInfo;
import com.dingding.bean.databean.response.ResGetUserOrder;
import com.dingding.bean.databean.response.ResPassengerPay;
import com.dingding.bean.databean.response.ResPayOrder;
import com.dingding.bean.databean.response.ResQueryOrderResult;
import com.dingding.bean.entity.UserLogin;
import com.dingding.bean.entity.Useraccount;
import com.dingding.bean.entity.Useraccountdetail;
import com.dingding.bean.entity.Userdetail;
import com.dingding.bean.entity.Userorder;
import com.dingding.cache.ordercache.OrderCache;
import com.dingding.common.core.beans.UserCoupon;
import com.dingding.common.core.beans.Userordert;
import com.dingding.common.core.config.ServiceCode;
import com.dingding.common.core.config.SystemCode;
import com.dingding.common.core.config.SystemConfig;
import com.dingding.common.core.sms.ISendMessage;
import com.dingding.common.core.sms.SendMessageFactory;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.dao.sql.UserOrderDaoSql;
import com.dingding.facade.queue.dto.msg.MessageRequestsDTO;
import com.dingding.facade.queue.facade.IQueueFacade;
import com.dingding.facde.activity.enums.AttendActivityEnum;
import com.dingding.message.MessageModel;
import com.dingding.message.PushModel;
import com.dingding.service.BaseService;
import com.dingding.service.userorderservice.IUserOrderService;
import com.dingding.util.SendPushUtil;

/**
 * 
 * @ClassName: UserOrderServiceImpl
 * @Description: 用户订单正式service实现
 * @author cheshaowei
 * @date 2015-10-21 上午10:44:04
 */
@SuppressWarnings("all")
public class UserOrderServiceImpl extends BaseService implements IUserOrderService {

	private Logger log = Logger.getLogger(this.getClass());


	// 判断是正式环境还是测试环境，如果是测试环境，则不增加取消次数
	private boolean environmentParam = SystemConfig.isEnv_system();
	
	@Resource(name = "queueFacade")
	private IQueueFacade queuefacade;

	/**
	 * @Title: cancelOrder
	 * @Description: 取消订单
	 * @param reqCancelOrder
	 *            取消订单客户端请求参数
	 * @author yhq
	 * @return Integer 返回取消成功或失败的响应码
	 * @throws @Override
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void cancelOrder(ReqCancelOrder reqCancelOrder, DataResponse dataResponse) {

		log.info(reqCancelOrder);
		// 验证取消订单时客户端传入参数是否为空
		boolean flagCancelOrder = this.validatecancelOrderParam(reqCancelOrder);

		if (!flagCancelOrder) {
			setStatus(dataResponse, SystemCode.DATA_NULL_ERROR);
			return;
		}

		try {
			// 添加查询条件
			Criterion criterion = Restrictions.eq("oid", reqCancelOrder.getOid());
			// 根据订单ID查询订单信息
			Userordert userordert = super.userOrderTDao.queryCriteriaUnResult(criterion, false);

			// 获取司机Id
			String driverId = null;
			// 获取乘客Id
			String passengerId = null;

			// 判断该订单是否存在
			if (userordert != null && ToolUtil.isNotBlank(userordert.getPlaceOrderUserId())
					&& userordert.getOrderStatus() != null && ToolUtil.isNotBlank(userordert.getOid())) {

				// 获取司机Id
				driverId = this.getDriverId(userordert, reqCancelOrder.getUserID());

				if (userordert.getPlaceOrderUserId().equals(driverId)
						&& ToolUtil.isNotBlank(userordert.getGrabOrderUserId())) {
					passengerId = userordert.getGrabOrderUserId();
				} else {
					passengerId = userordert.getPlaceOrderUserId();
				}

				// 该订单的订单状态
				Integer orderStatsu = userordert.getOrderStatus();

				if (orderStatsu == ServiceCode.ORDER_STATUS_COMPLETE) {// 判断订单状态是否是已完成
					// 订单已完成
					setStatus(dataResponse, SystemCode.PASSENGER_COMPLETE_ORDER_ERROR);
				} else if (orderStatsu == ServiceCode.ORDER_STATUS_CANCEL) {// 判断订单状态是否是已取消
					// 订单已取消
					setStatus(dataResponse, SystemCode.PASSENGER_CANCEL_ORDER_ERROR);
				} else {

					// 乘客取消，给乘客退款
					// 判断该订单状态是否为已支付，如果为已支付，则给乘客退款
					if (userordert.getOrderStatus().equals(ServiceCode.ORDER_STATUS_PAID)) {
						// 给乘客退款，返回值 1：退款成功 0:退款失败
						int row = passengerRefund(dataResponse, userordert, passengerId);

						// 如果退款失败，则抛出异常，终止操作
						if (row == 0) {
							throw new RuntimeException();
						}

					}

					// 主动取消的用户Id
					String activeCancelOrderUserId = null;
					// 要推送的用户Id
					String pushUserId = null;

					if (reqCancelOrder.getCancelNumber() == 1) { // 司机主动取消
						activeCancelOrderUserId = driverId;
						pushUserId = passengerId;
					} else if (reqCancelOrder.getCancelNumber() == 2) { // 乘客主动取消
						activeCancelOrderUserId = passengerId;
						pushUserId = driverId;
					}

					// 给司机发送短信和推送
					// 获取发送短信手机号和推送内容
					PushCancelOrder pushCancelOrder = null;

					// 判断被取消的订单是否为待支付或已支付，如果是则发送短信并推送，否则不处理
					if (orderStatsu == ServiceCode.ORDER_STATUS_PAY || orderStatsu == ServiceCode.ORDER_STATUS_PAID) {

						// 获取发送短信手机号和推送内容
						pushCancelOrder = super.userOrderTDao.getPushCancelOrderInfo(activeCancelOrderUserId,
								pushUserId);

						// 判断获取内容是否为空
						if (pushCancelOrder == null) {
							throw new RuntimeException();
						}

						// 订单Id
						pushCancelOrder.setOid(userordert.getOid());
						// 订单状态
						pushCancelOrder.setOrderStatus(userordert.getOrderStatus());
						// 订单取消原因
						pushCancelOrder.setCancelDesc(reqCancelOrder.getCancelDesc());
						// 订单状态
						pushCancelOrder.setOrderStatus(ServiceCode.ORDER_STATUS_CANCEL);

						// 从缓存中删除订单信息(订单Id和订单状态)
						boolean flagCache = this.cancelCache(reqCancelOrder.getOid());

						if (!flagCache) {
							return;
						}

						// 取消订单成功，给司机发送短信
						this.passengerPaySendMessage(pushCancelOrder);

						// 取消订单成功，给司机推送消息
						this.passengerPayPushMessage(pushCancelOrder, ServiceCode.CANEL_ORDER);
						// 发送邮件
						this.sendEmail(pushCancelOrder, userordert);

					}

					// 将userOrdert(临时表,存储待抢单、待支付和已支付状态的订单)中的值赋给userOrder(正式表,存储已完成和已取消的订单)
					Userorder userOrder = this.getUserorder(userordert);
					// 1:司机主动取消 2:乘客主动取消
					userOrder.setCancelNumber(reqCancelOrder.getCancelNumber());
					// 订单状态
					userOrder.setOrderStatus(ServiceCode.ORDER_STATUS_CANCEL);
					// 取消类型
					userOrder.setCancelType(reqCancelOrder.getCancelType());
					// 取消原因
					userOrder.setCancelDesc(reqCancelOrder.getCancelDesc());
					// 取消时间
					userOrder.setCancelTime(new Date());
					// 取消订单用户Id
					userOrder.setCancelUserId(reqCancelOrder.getUserID());

					// 返还优惠券
					if (ToolUtil.isNotBlank(userordert.getUcId())) {
						// 添加查询条件
						Criterion criter = Restrictions.eq("ucId", userordert.getUcId());

						UserCoupon userCoupon = super.userCouponDao.queryCriteriaUnResult(criter, false);

						if (userCoupon != null && userCoupon.getCouponStatus() != null
								&& userCoupon.getCouponStatus() == 3) {
							userCoupon.setCouponStatus(2);
						}
					}

					// 删除临时表中的订单数据(该订单状态为已完成或已取消)
					super.userOrderTDao.delete(userordert);

					// 添加订单(状态为已完成或已取消的订单)
					super.userOrderDao.save(userOrder);

					if (environmentParam) {
						// 用户取消成功，增加一次每日取消次数
						this.addCancelNumber(activeCancelOrderUserId);
					}

					// 取消订单成功，设置响应码以及响应消息
					setStatus(dataResponse, SystemCode.SUCCESS);

					return;
				}

			} else {
				// 订单不存在，设置响应码以及响应消息
				setStatus(dataResponse, SystemCode.ORDER_NOT_EXIST_ERROR);
				return;
			}
		} catch (Exception e) {
			log.error("取消订单时出现异常  类：" + this.getClass() + " 方法：cancelOrder()", e);
			// 网络异常，设置响应码以及响应消息
			setStatus(dataResponse, SystemCode.ERROR);
			return;
		}

	}

	/**
	 * @Title: sendEmail @Description: 发送邮件 @author yuHaiQing @return boolean
	 *         返回类型 @throws
	 */
	public boolean sendEmail(Object object, Userordert userordert) {

		Map<String, Object> title = new HashMap<String, Object>();

		String orderStr = "";

		if (userordert.getIsLongDistance() != null && userordert.getIsLongDistance() == 1) {
			orderStr = "(同城)";
		} else if (userordert.getIsLongDistance() != null && userordert.getIsLongDistance() == 2) {
			orderStr = "(长途)";
		}

		title.put("orderType", orderStr);

		// 邮件内容
		Map<String, Object> root = new HashMap<String, Object>();

		root.put("oid", userordert.getOid());// 订单Id

		if (object instanceof PushCompetitiveOrder) {
			PushCompetitiveOrder pushCompetitiveOrder = (PushCompetitiveOrder) object;

			root.put("lisencePlate", pushCompetitiveOrder.getLicensePlate());// 车牌号
			root.put("driverName", pushCompetitiveOrder.getDriverName());// 司机姓名

			title.put("orderStatus", "(接单)");

		} else if (object instanceof PushCancelOrder) {
			PushCancelOrder pushCancelOrder = (PushCancelOrder) object;

			root.put("lisencePlate", pushCancelOrder.getLisencePlate());// 车牌号
			root.put("driverName", pushCancelOrder.getDriverName());// 司机姓名

			title.put("orderStatus", "(已取消)");

		}

		if (userordert.getCreateTime() != null) {
			root.put("createTime", userordert.getCreateTime());// 下单时间
		}
		if (userordert.getSetOutTime() != null) {
			root.put("setOutTime", userordert.getSetOutTime());// 出发时间
		}
		if (ToolUtil.isNotBlank(userordert.getStartAddress())) {
			root.put("startAddress", userordert.getStartAddress());// 起点
		}
		if (ToolUtil.isNotBlank(userordert.getEndAddress())) {
			root.put("endAddress", userordert.getEndAddress());// 终点
		}

		try {
			super.emailSend.senMail(title, "emailTitle.ftl", root, "emailContext.ftl");
		} catch (Exception e) {
			log.error("发送邮件时出现异常  类：" + this.getClass() + " sendEmail()", e);
			return false;
		}

		return true;
	}

	/**
	 * @Title: validatecancelOrderParam @Description: 验证取消订单客户端传入参数是否为空 @param
	 *         reqCancelOrder 客户端传入参数 @return boolean 返回类型 @throws
	 */
	public boolean validatecancelOrderParam(ReqCancelOrder reqCancelOrder) {

		if (reqCancelOrder == null // 客户端传入参数对象是否为空
				|| ToolUtil.isBlank(reqCancelOrder.getUserID()) // 取消用户Id是否为空
				|| ToolUtil.isBlank(reqCancelOrder.getOid()) // 订单Id是否为空
				|| reqCancelOrder.getCancelType() == null // 取消类型是否为空
				|| reqCancelOrder.getUserType() == null) { // 当前用户类型是否为空

			return false;
		}

		return true;
	}

	/**
	 * @Title: addCancelNumber @Description: 给主动取消的用户添加一个 @param @return void
	 *         返回类型 @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void addCancelNumber(String userId) {
		// 添加一个用户Id作为查询条件
		Criterion criterion = Restrictions.eq("uid", userId);

		// 根据用户Id获取登录信息
		UserLogin userLogin = super.userLoginDao.queryCriteriaUnResult(criterion, false);

		// 判断如果登录信息不为空，则给该用户增加一次取消
		if (userLogin != null) {
			userLogin.setCancelNumber(userLogin.getCancelNumber() + 1);
		}

	}

	/**
	 * @Title: passengerRefund @Description: 订单取消-给乘客退款 @param dataResponse
	 *         响应Bean @param userordert 订单信息 @param reqCancelOrder
	 *         客户端请求参数 @author yhq @return int 返回类型 @throws
	 */
	public int passengerRefund(DataResponse dataResponse, Userordert userordert, String passengerId) {

		int row = 0;

		try {
			// 执行给乘客退款操作 返回值 1：退款成功 0:退款失败
			row = super.userAccountDao.updateSqlRow(UserOrderDaoSql.PASSENGER_REFUND,
					userordert.getTotalMoney().subtract(userordert.getCouponMoney()), passengerId);

			// 判断乘客退款操作是否成功
			if (row == 0) {
				log.info("给乘客退款失败");
				setStatus(dataResponse, SystemCode.PASSENGER_REFUND_ERROR);
			}

		} catch (Exception e) {
			log.info("取消订单给乘客退款时，出现异常  类：" + this.getClass() + " passengerRefund", e);
		}

		return row;
	}

	/**
	 * @Title: cancelOrder
	 * @Description: 确认到达
	 * @param reqCancelOrder
	 *            确认到达-客户端请求参数
	 * @param dataResponse
	 *            响应对象
	 * @author yhq
	 * @return void
	 * @throws @Override
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void confirmArrival(ReqConfirmArrival reqConfirmArrival, DataResponse dataResponse) {

		// 验证确认到达客户端传入参数是否为空
		boolean isTrue = this.isValidateConfirmArrivalParamTrue(reqConfirmArrival);
		if (!isTrue) {
			// 客户端请求参数为空
			log.error("确认到达请求参数为空:" + reqConfirmArrival.toString());
			setStatus(dataResponse, SystemCode.DATA_NULL_ERROR);
			return;
		}

		// 根据订单Id获取订单信息,并做相关验证
		Userordert userordert = this.confirmArrivalValidate(dataResponse, reqConfirmArrival.getOid());

		// 判断该订单是否为空
		if (userordert == null) {
			return;
		}

		// 转账操作
		Boolean flag = transferAccounts(dataResponse, reqConfirmArrival.getUserId(), userordert);

		// 判断如果转账失败，则终止操作
		if (!flag) {
			throw new RuntimeException("转账失败，则终止操作");
		}

		/** 确认到达，给司机推送并发短信开始 **/

		// 获取司机Id
		String driverId = this.getDriverId(userordert, reqConfirmArrival.getUserId());

		// 根据乘客Id或车主Id，获取发送短信和推送内容的信息
		PushConfirmArrival pushConfirmArrival = super.userOrderTDao.getConfirmArrival(reqConfirmArrival.getUserId(),
				driverId);

		// 判断获取信息是否为空
		if (pushConfirmArrival == null) {
			setStatus(dataResponse, SystemCode.ERROR);
			throw new RuntimeException(); // 制造异常，终止乘客确认到达
		}

		// 订单Id
		pushConfirmArrival.setOid(userordert.getOid());

		/** 确认到达，给司机推送并发短信开始 **/

		// 修改用户状态
		userordert.setOrderStatus(ServiceCode.ORDER_STATUS_COMPLETE);

		// 订单状态
		pushConfirmArrival.setOrderStatus(userordert.getOrderStatus());

		// 将userOrdert(临时表,存储待抢单、待支付和已支付状态的订单)中的值赋给userOrder(正式表,存储已完成和已取消的订单)
		Userorder userOrder = this.getUserorder(userordert);
		// 乘客确认到达时间
		userOrder.setEndTime(new Date());

		try {

			// 删除临时表中的订单数据(该订单状态为已完成或已取消)
			super.userOrderTDao.delete(userordert);

			// 添加订单(状态为已完成或已取消的订单)
			super.userOrderDao.save(userOrder);

			// 判断是正式环境还是测试环境(测试环境不需要增加接单次数)
			if (environmentParam) {
				// 增加一次完成订单数
				this.addReachOrderNumber(userOrder);
			}

		} catch (Exception e) {
			log.error("将已完成或已取消的订单从订单临时表转入正式表时出现异常  类：" + this.getClass() + " 方法：confirmArrival()", e);
			setStatus(dataResponse, SystemCode.ERROR);
			return;
		}

		// 从订单中删除缓存
		boolean flagCache = this.cancelCache(reqConfirmArrival.getOid());

		if (!flagCache) {
			return;
		}

		/** 调用第三方接口开始 **/
		// 参加活动,类型为完成订单
//		BigDecimal integral = activityService.attendActivity(driverId, AttendActivityEnum.COMPLETE_ORDER);
//		if (integral.compareTo(new BigDecimal(0)) != 0) {
//			// 将参加活动所赠积分添加到订单表中
//			boolean status = userOrderTDao.updateCurrentOrderReceiveIntegral(integral,
//					reqConfirmArrival.getOid());
//		}
		// 获取给司机发送短信内容
		pushConfirmArrival.setIntegral(new BigDecimal(0));
		// 确认到达成功，给司机发送短信
		this.passengerPaySendMessage(pushConfirmArrival);

		// 确认到达成功，给司机推送消息
		this.passengerPayPushMessage(pushConfirmArrival, ServiceCode.CONFIRM_ARRIVAL);

		/** 调用第三方接口结束 **/
		// 确认到达成功，设置响应码以及响应消息
		setStatus(dataResponse, SystemCode.SUCCESS);

	}

	/**
	 * @Title: cancelCache @Description: 根据订单ID删除缓存 @param oid 订单Id @return
	 *         boolean 返回类型 true:参数正确 false:参数错误 @throws
	 */
	public boolean cancelCache(String oid) {

		// 从缓存中获取订单状态
		OrderCache orderCache = new OrderCache();
		// 从订单中删除缓存
		boolean isDelSucc = orderCache.delOrderStatus(oid);
		if (!isDelSucc) { // 缓存中的订单为不是待抢单状态
			log.error("将订单从缓存中删除失败!订单编号：" + oid);
			return false;
		}

		return true;
	}

	/**
	 * @Title: validateConfirmArrivalParam @Description:
	 *         验证确认到达客户端传入参数是否为空 @param reqConfirmArrival 确认到达客户端传入参数 @return
	 *         boolean 返回类型 true:参数正确 false:参数错误 @throws
	 */
	private boolean isValidateConfirmArrivalParamTrue(ReqConfirmArrival reqConfirmArrival) {

		// 请求bean
		if (reqConfirmArrival == null) { // 用户Id是否为空
			return false;
		}
		// 订单id
		if (ToolUtil.isBlank(reqConfirmArrival.getOid())) {
			return false;
		}
		// 乘客id
		if (ToolUtil.isBlank(reqConfirmArrival.getUserId())) {
			return false;
		}

		return true;
	}

	/**
	 * @Title: addReachOrderNumber @Description: 乘客确认到达-给司机和乘客的搭车次数加一 @param
	 *         userOrder 订单信息 @return void 返回类型 @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = RuntimeException.class)
	public boolean addReachOrderNumber(Object object) {

		// 下单用户
		String driverId = null;
		// 抢单用户
		String passengerId = null;
		// 是否使用了优惠券
		Boolean flag = false;

		if (object instanceof Userorder) {

			Userorder userorder = (Userorder) object;

			// 乘客下单
			if (userorder.getOrderType() == 1) {

				driverId = userorder.getGrabOrderUserId();
				passengerId = userorder.getPlaceOrderUserId();

			} else if (userorder.getOrderType() == 2) {// 司机下单

				driverId = userorder.getPlaceOrderUserId();
				passengerId = userorder.getGrabOrderUserId();

			}

			if (ToolUtil.isNotBlank(userorder.getUcId())) {
				flag = true;
			}

		} else if (object instanceof PushAutomaticCancelOrder) {

			PushAutomaticCancelOrder pushAutomaticCancelOrder = (PushAutomaticCancelOrder) object;

			driverId = pushAutomaticCancelOrder.getDriverId();
			passengerId = pushAutomaticCancelOrder.getPassengerId();

			if (ToolUtil.isNotBlank(pushAutomaticCancelOrder.getUcId())) {
				flag = true;
			}
		}

		// 下单用户
		Criterion criterionPlace = Restrictions.eq("uid", driverId);
		// 获取下单用户登录信息
		UserLogin place = null;
		try {
			place = super.userLoginDao.queryCriteriaUnResult(criterionPlace, false);
		} catch (Exception e) {
			log.info("给用户增加一次接单次数时出现异常   类：" + this.getClass() + " addReachOrderNumber", e);
			return false;
		}

		// 如果下单用户登录信息不为空，则给其完成订单次数加一
		if (place != null) {
			place.setPublishNumber(place.getPublishNumber() + 1);
		} else {
			return false;
		}

		// 抢单用户
		Criterion criterionGrab = Restrictions.eq("uid", passengerId);
		// 获取抢单用户登录信息
		UserLogin grab = null;
		try {
			grab = super.userLoginDao.queryCriteriaUnResult(criterionGrab, false);
		} catch (Exception e) {
			log.info("给用户增加一次接单次数时出现异常   类：" + this.getClass() + " addReachOrderNumber", e);
			return false;
		}

		// 如果抢单用户登录信息不为空，则给其完成订单次数加一
		if (grab != null) {
			// 完成订单次数
			grab.setPublishNumber(grab.getPublishNumber() + 1);
			if (flag) {
				// 优惠券使用次数
				grab.setCouponNumber(grab.getCouponNumber() - 1);
			}
		} else {
			return false;
		}

		return true;
	}

	/**
	 * @Title: confirmArrivalValidate @Description: 乘客确认到达-获取订单信息并进行验证 @param
	 *         dataResponse 响应客户端Bean @param oid 订单Id @author yhq @return
	 *         Userordert 返回类型 @throws
	 */
	public Userordert confirmArrivalValidate(DataResponse dataResponse, String oid) {

		Userordert userordert = null;

		try {
			// 将订单Id添加为查询条件
			Criterion criterion = Restrictions.eq("oid", oid);
			userordert = super.userOrderTDao.queryCriteriaUnResult(criterion, false);
		} catch (Exception e) {
			log.info("根据订单Id获取订单信息时出现异常，类：" + this.getClass() + " confirmArrival()");
			setStatus(dataResponse, SystemCode.ERROR);
			return null;
		}

		// 判断该订单是否存在
		if (userordert == null || userordert.getOrderStatus() == null) {
			// 该订单不存在
			setStatus(dataResponse, SystemCode.ORDER_NOT_EXIST_ERROR);
			return null;
		}

		// 判断该订单的订单状态是否为已支付状态
		if (userordert.getOrderStatus() != ServiceCode.ORDER_STATUS_PAID) {
			// 不为已支付状态
			setStatus(dataResponse, SystemCode.NOT_ALREADY_PAY_ERROR);
			return null;
		}

		return userordert;
	}

	/**
	 * @Title: transferAccounts @Description: 转账 @param userId 转账给该用户 @param
	 *         totalMoney 转账金额 @author yhq @return void 返回类型 @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean transferAccounts(DataResponse dataResponse, String userId, Userordert userordert) {

		// 根据用户Id(乘客),获取用户账户信息
		Useraccount passenger = super.userAccountService.getUserAccountByUserId(userId, dataResponse);

		// 创建存储司机Id的对象
		String driverId = null;

		/**
		 * 获取司机Id 1.订单为乘客下单时，判断如果当前用户等于下单用户，则该订单的抢单用户为司机角色
		 * 2.订单为司机下单时，判读如果当前用户等于抢单用户，则该订单的抢单用户为司机角色 3.否则其他情况则为下单用户为司机。
		 */

		if (ToolUtil.isNotBlank(userordert.getPlaceOrderUserId())
				&& ToolUtil.isNotBlank(userordert.getGrabOrderUserId()) && userordert.getOrderType() != null
				&& userordert.getTotalMoney() != null && userordert.getDistance() != null) {
			// 获取司机ID
			if (userordert.getPlaceOrderUserId().equals(userId) && userordert.getOrderType() == 1) {
				driverId = userordert.getGrabOrderUserId();
			} else if (userordert.getGrabOrderUserId().equals(userId) && userordert.getOrderType() == 2) {
				driverId = userordert.getPlaceOrderUserId();
			}
		} else {
			return false;
		}

		// 根据用户Id(司机),获取用户账户信息
		Useraccount driver = super.userAccountService.getUserAccountByUserId(driverId, dataResponse);

		// 根据乘客Id获取用户详细信息
		Userdetail detailPassenger = super.userDetailService.getUserDetail(userId, dataResponse);

		// 根据司机Id获取用户详细信息
		Userdetail detailDriver = super.userDetailService.getUserDetail(driverId, dataResponse);

		// 判断用户账户是否为空
		if (passenger == null || driver == null || detailDriver == null || detailPassenger == null) {
			return false;
		}

		if (passenger.getTotalExpend() == null || driver.getCurrencyAmount() == null || driver.getTotalIncome() == null
				|| detailPassenger.getTotalTake() == null || detailDriver.getTotalWeldingProcess() == null
				|| detailPassenger.getTotalTakeNumber() == null
				|| detailDriver.getTotalWeldingProcessNumber() == null) {
			return false;
		}

		// 乘车搭车累计支出
		passenger.setTotalExpend(passenger.getTotalExpend().add(userordert.getTotalMoney()));

		// 给司机转账
		driver.setCurrencyAmount(driver.getCurrencyAmount().add(userordert.getTotalMoney()).add(new BigDecimal(2)));

		// 司机搭人累计收入
		driver.setTotalIncome(driver.getTotalIncome().add(userordert.getTotalMoney()).subtract(new BigDecimal(2)));

		// 乘客累计搭乘
		detailPassenger.setTotalTake(detailPassenger.getTotalTake());

		// 司机累计接乘
		detailDriver.setTotalWeldingProcess(detailDriver.getTotalWeldingProcess().add(userordert.getDistance()));

		// 乘客总搭乘次数+1
		detailPassenger.setTotalTakeNumber(detailPassenger.getTotalTakeNumber() + 1);

		// 司机总接乘次数+1
		detailDriver.setTotalWeldingProcessNumber(detailDriver.getTotalWeldingProcessNumber() + 1);

		boolean isSuccess = this.addUserAccountDetail(passenger.getLoginId(), driverId, userordert);

		return isSuccess;

	}

	/**
	 * @Title: addUserAccountDetail @Description: 自动确认到达时给乘客和车主添加账户记录 @param
	 *         passengerId 乘客id @param driverId 车主id @param orderMoney
	 *         钱数 @author lijinchao @return boolean @throws
	 */
	private boolean addUserAccountDetail(String passengerId, String driverId, Userordert userordert) {
		// 创建用户交易明细对象
		Useraccountdetail passengerAccountdetail = new Useraccountdetail();
		// 交易明细Id
		passengerAccountdetail.setUadId(ToolUtil.getUid());
		// 用户Id
		passengerAccountdetail.setUserId(passengerId);
		// 交易金额
		passengerAccountdetail.setTradeMoney(userordert.getTotalMoney());
		// 实际支付金额
		passengerAccountdetail.setActualPaymentMoney(userordert.getAlipayMoney().subtract(userordert.getPayMoney()));
		// 优惠金额
		passengerAccountdetail.setCouponMoney(userordert.getCouponMoney());
		// 交易类型 1:收入 2: 支出 3:提现 4:取消
		passengerAccountdetail.setTradeType(2);
		// 交易时间
		passengerAccountdetail.setTradeTime(new Date());

		// 创建司机用户交易明细对象
		Useraccountdetail driverAccountdetail = new Useraccountdetail();
		// 交易明细Id
		driverAccountdetail.setUadId(ToolUtil.getUid());
		// 用户Id
		driverAccountdetail.setUserId(driverId);
		// 交易金额
		driverAccountdetail.setTradeMoney(userordert.getTotalMoney().subtract(new BigDecimal(2)));
		// 交易类型 1:收入 2: 支出 3:提现 4:取消
		driverAccountdetail.setTradeType(1);
		// 交易时间
		driverAccountdetail.setTradeTime(new Date());

		try {
			super.userAccountDetailDao.save(passengerAccountdetail);
			super.userAccountDetailDao.save(driverAccountdetail);
		} catch (Exception e) {
			log.error("给司机转账，保存用户交易明细时出现异常   类：" + this.getClass() + " transferAccounts()", e);
			return false;
		}

		return true;
	}

	/**
	 * @Title: passengerPay
	 * @Description: 乘客支付
	 * @param reqPassengerPay
	 *            乘客支付-客户端请求参数
	 * @param dataResponse
	 *            响应对象
	 * @author yhq
	 * @return void
	 * @throws @Override
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void passengerPay(ReqPassengerPay reqPassengerPay, DataResponse dataResponse) {

		// 验证乘客支付时客户端传入参数是否为空
		boolean isTrue = this.isValidatePassengerPayParamTrue(reqPassengerPay);

		if (!isTrue) {
			log.error("乘客支付请求参数为空:" + reqPassengerPay.toString());
			setStatus(dataResponse, SystemCode.DATA_NULL_ERROR);
			return;
		}

		// 验证并获取该订单的订单信息
		Userordert userordert = this.getValidateAndUserordert(reqPassengerPay, dataResponse);

		// 判断返回的订单信息是否为空
		if (userordert == null || ToolUtil.isBlank(userordert.getOid()) || userordert.getOrderStatus() == null) {
			// 如果为空，则终止乘客支付操作
			return;
		}

		PushCompetitiveOrder pushCompetitiveOrder = null;

		// 判断如果支付宝支付金额为0,
		if (userordert.getAlipayMoney() != null && userordert.getAlipayMoney().compareTo(new BigDecimal(0)) == 0) {
			// 乘客支付-扣款
			pushCompetitiveOrder = passengerDebit(userordert, pushCompetitiveOrder, dataResponse);

			// 乘客支付失败，终止支付流程
			// 发送邮件内容为空，终止支付流程
			if (pushCompetitiveOrder == null) {
				return;
			}

			// 获取发送短信和推送消息
			// 获取司机Id
			String driverId = this.getDriverId(userordert, reqPassengerPay.getPassengerID());

			// 乘客支付成功发送短信
			this.passengerPaySendInfo(reqPassengerPay.getPassengerID(), driverId, userordert);

			// 发送邮件
			this.sendEmail(pushCompetitiveOrder, userordert);

		}

		// 创建乘客支付响应Bean
		ResPassengerPay resPassengerPay = new ResPassengerPay();

		// 订单Id
		resPassengerPay.setOid(userordert.getOid());
		// 支付宝支付金额
		resPassengerPay.setPayMoney(userordert.getAlipayMoney());

		// 向服务器数据响应封装对象添加返回内容
		dataResponse.setResponseBody(resPassengerPay);

		// 向订单添加支付宝支付金额和叮币支付金额成功
		setStatus(dataResponse, SystemCode.SUCCESS);

	}

	/**
	 * @Title: payOrder
	 * @Description: 乘客支付订单
	 * @param reqPayOrder
	 *            乘客支付-客户端请求参数
	 * @author fengshuonan
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void payOrder(ReqPayOrder reqPayOrder, DataResponse dataResponse) {

		// 创建乘客支付响应Bean
		ResPayOrder resPayOrder = new ResPayOrder();

		// 验证乘客支付时客户端传入参数是否为空
		boolean isTrue = this.validateReqPayOrder(reqPayOrder);

		if (!isTrue) {
			log.error("乘客支付请求参数为空:" + reqPayOrder.toString());
			setStatus(dataResponse, SystemCode.DATA_NULL_ERROR);
			return;
		}

		// 验证并获取该订单的订单信息
		Userordert userordert = this.validateOrderInfo(reqPayOrder, dataResponse);

		// 判断返回的订单信息是否为空
		if (userordert == null || ToolUtil.isBlank(userordert.getOid()) || userordert.getOrderStatus() == null) {
			// 如果为空，则终止乘客支付操作
			return;
		}

		PushCompetitiveOrder pushCompetitiveOrder = null;

		// 判断如果支付宝支付金额为0,
		if (userordert.getAlipayMoney() != null && userordert.getAlipayMoney().compareTo(new BigDecimal(0)) == 0) {
			// 乘客支付-扣款
			pushCompetitiveOrder = passengerDebit(userordert, pushCompetitiveOrder, dataResponse);

			// 乘客支付失败，终止支付流程
			// 发送邮件内容为空，终止支付流程
			if (pushCompetitiveOrder == null) {
				return;
			}

			// 获取发送短信和推送消息
			// 获取司机Id
			String driverId = this.getDriverId(userordert, reqPayOrder.getPassengerID());

			// 乘客支付成功发送短信
			this.passengerPaySendInfo(reqPayOrder.getPassengerID(), driverId, userordert);

			// 发送邮件
			this.sendEmail(pushCompetitiveOrder, userordert);

		} else if (userordert.getAlipayMoney() != null && userordert.getAlipayMoney().compareTo(new BigDecimal(0)) != 0) {

			/**** add 03-10 fengshuonan ****/
			// 如果支付方式为微信支付,向微信发送信息
			if (reqPayOrder.getPayType() == 2) {

				// 向微信服务器发送下单信息
				WechatPayApi wepay = new WechatPayApi();
				WechatPayOrderResponse payResponse = wepay.placeAnOrder(WechatPayApi.createAppPayRequest(
						userordert.getOid(), userordert.getAlipayMoney().multiply(new BigDecimal(100)).intValue(), reqPayOrder.getIpAddress()));

				// 如果微信下单没有成功
				if (payResponse == null && (payResponse.getReturn_code().equals("FAIL")
						|| payResponse.getResult_code().equals("FAIL"))) {
					setStatus(dataResponse, SystemCode.ERROR);
					return;
				}

				// 根据返回结果进行二次签名
				SecondSign secondSign = WechatPayApi.getSecondSign(payResponse.getPrepay_id(),
						payResponse.getNonce_str());

				// 设置服务器的微信订单生成结果信息
				resPayOrder.setPrepayid(secondSign.getPrepayid());
				resPayOrder.setNoncestr(secondSign.getNoncestr());
				resPayOrder.setTimestamp(secondSign.getTimestamp());
				resPayOrder.setSign(secondSign.getSign());
			}
		}

		// 订单Id
		resPayOrder.setOid(userordert.getOid());
		// 支付宝支付金额
		resPayOrder.setPayMoney(userordert.getAlipayMoney());

		// 向服务器数据响应封装对象添加返回内容
		dataResponse.setResponseBody(resPayOrder);

		// 向订单添加支付宝支付金额和叮币支付金额成功
		setStatus(dataResponse, SystemCode.SUCCESS);
	}

	/**
	 * @Title: validateReqPayOrder
	 * @Description: 验证请求支付的参数是否为空
	 * @author fengshuonan
	 * @return boolean
	 */
	private boolean validateReqPayOrder(ReqPayOrder reqPayOrder) {

		// 请求bean
		if (reqPayOrder == null) { // 支付总金额是否为空
			return false;
		}
		// 订单id
		if (ToolUtil.isBlank(reqPayOrder.getOid())) {
			return false;
		}
		// 乘客id
		if (ToolUtil.isBlank(reqPayOrder.getPassengerID())) {
			return false;
		}
		// 支付宝支付金额
		if (reqPayOrder.getAlipayMoney() == null) {
			return false;
		}
		// 叮币支付金额
		if (reqPayOrder.getPayMoney() == null) {
			return false;
		}
		// 优惠金额
		if (reqPayOrder.getCouponMoney() == null) {
			return false;
		}
		// 支付类型
		if (reqPayOrder.getPayType() == null) {
			return false;
		}
		// 客户端ip地址（如果是微信支付，必须传ip地址）
		if (reqPayOrder.getPayType() == 2 && ToolUtil.isBlank(reqPayOrder.getIpAddress())) {
			return false;
		}

		return true;

	}

	/**
	 * @Title: passengerPaySendInfo @Description: 乘客支付发送短信以及验证码 @param
	 *         passengerId 乘客Id @param driverId 司机Id @param userordert
	 *         订单对象 @return void 返回类型 @throws
	 */
	@Override
	@Transactional(readOnly = true)
	public void passengerPaySendInfo(String passengerId, String driverId, Userordert userordert) {

		// 获取乘客支付推送内容
		PushPassengerPay pushPassengerPay = super.userOrderTDao.getPassengerPayPushInfo(passengerId, driverId);

		// 判断乘客支付推送内容是否为空
		if (pushPassengerPay == null) {
			log.info("订单" + userordert.getOid() + "在乘客支付时，给司机" + driverId + "推送失败");
		}

		// 乘客Id(用来查看乘客信息)
		pushPassengerPay.setPassengerId(passengerId);
		// 订单状态
		pushPassengerPay.setOrderStatus(userordert.getOrderStatus());
		// 父订单Id
		pushPassengerPay.setParentOrder(userordert.getParOrderId());
		// 子订单Id
		pushPassengerPay.setSubOrder(userordert.getOid());

		// 乘客支付成功，给司机发送短信
		this.passengerPaySendMessage(pushPassengerPay);

		// 乘客支付成功，给司机推送消息
		this.passengerPayPushMessage(pushPassengerPay, ServiceCode.PASSENGER_PAY);

	}

	/**
	 * @Title: validatePassengerPayParam @Description:
	 *         验证乘客支付时客户端传入的参数是否为空 @param 验证乘客支付客户端请求参数是否为空 @return true 参数正确
	 *         false 参数错误 @author lijinchao @throws
	 */
	private boolean isValidatePassengerPayParamTrue(ReqPassengerPay reqPassengerPay) {

		// 请求bean
		if (reqPassengerPay == null) { // 支付总金额是否为空
			return false;
		}
		// 订单id
		if (ToolUtil.isBlank(reqPassengerPay.getOid())) {
			return false;
		}
		// 乘客id
		if (ToolUtil.isBlank(reqPassengerPay.getPassengerID())) {
			return false;
		}
		// 支付宝支付金额
		if (reqPassengerPay.getAlipayMoney() == null) {
			return false;
		}
		// 叮币支付金额
		if (reqPassengerPay.getPayMoney() == null) {
			return false;
		}
		// 优惠金额
		if (reqPassengerPay.getCouponMoney() == null) {
			return false;
		}

		return true;
	}

	/**
	 * @Title: getDriverId @Description: 根据订单信息和乘客Id获取司机Id @param userordert
	 *         订单信息 @param passengerId 乘客Id @author yhq @return String
	 *         返回类型 @throws
	 */
	public String getDriverId(Userordert userordert, String passengerId) {

		// 创建一个司机Id对象
		String driverId = null;

		if (userordert.getOrderType() == 2) {
			driverId = userordert.getPlaceOrderUserId();
		} else {
			driverId = userordert.getGrabOrderUserId();
		}

		return driverId;
	}

	/**
	 * @Title: passengerPaySendMessage @Description:
	 *         给司机发送短信(乘客支付与乘客确认到达共用) @param Object 推送内容(乘客支付与乘客确认的推送Id) @author
	 *         yhq @return void 返回类型 @throws
	 */
	public void passengerPaySendMessage(Object obj) {

		// 司机手机号
		String phoneNo = null;
		// 给司机发送短信内容
		String sendText = null;

		if (obj instanceof PushPassengerPay) {
			PushPassengerPay pushPassengerPay = (PushPassengerPay) obj;

			// 获取司机手机号
			phoneNo = pushPassengerPay.getTellPhone();
			// 获取给司机发送短信内容
			sendText = MessageModel.passengerPaySuccess(pushPassengerPay.getPassengerName());

		} else if (obj instanceof PushConfirmArrival) {
			PushConfirmArrival pushConfirmArrival = (PushConfirmArrival) obj;

			// 获取司机手机号
			phoneNo = pushConfirmArrival.getTellPhone();

			sendText = MessageModel.confirmArrive(pushConfirmArrival.getPassengerName(),
					pushConfirmArrival.getIntegral());

		} else if (obj instanceof PushCancelOrder) {

			PushCancelOrder pushCancelOrder = (PushCancelOrder) obj;
			// 获取司机手机号
			phoneNo = pushCancelOrder.getTellPhone();
			// 获取给司机发送短信内容
			sendText = MessageModel.cancelOrder(pushCancelOrder.getPassengerName(), pushCancelOrder.getCancelDesc());
		}

		// 调用第三方接口，发送短信
		MessageRequestsDTO messageRequestsDTO = new MessageRequestsDTO();
		messageRequestsDTO.setTelPhone(phoneNo);
		messageRequestsDTO.setMessageContent(sendText);
		boolean flag = queuefacade.addMessageToQueue(JSONUtil.toJSONString(messageRequestsDTO));

		// 判断短信是否发送成功
		if (!flag && obj instanceof PushPassengerPay) {
			log.info("乘客支付成功时，给司机发送短信失败");
		} else if (!flag && obj instanceof PushConfirmArrival) {
			log.info("乘客确认到达时，给司机发送短信失败");
		} else if (!flag && obj instanceof PushCancelOrder) {
			log.info("乘客取消订单时，给司机发送短信失败");
		}
	}

	/**
	 * @Title: passengerPayPushMessage @Description: 乘客确认到达-给司机推送消息 @param
	 *         pushPassengerPay 推送消息内容 @author yhq @return void 返回类型 @throws
	 */
	public void passengerPayPushMessage(Object obj, String modular) {

		// 推送Id
		String registrationID = null;
		// 通知标题
		String alert = null;
		// 推送内容标题
		String msgTitle = null;
		// 推送内容
		String msgContent = null;
		// 设备类型
		String sysType = null;

		// 推送Bean
		PushData pushData = new PushData();

		// 推送序号(时间戳)
		pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
		// 推送时间
		pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
		// 模块
		pushData.setModular(modular);

		// 判断传入的参数类型(来确定是乘客支付还是乘客确认到达)
		if (obj instanceof PushPassengerPay) {

			// 乘客确认到达，将Object[]转型为PushPassengerPay
			PushPassengerPay pushPassengerPay = (PushPassengerPay) obj;

			// 推送内容
			pushData.setResponseBody(pushPassengerPay);

			// 推送Id
			registrationID = pushPassengerPay.getDriverId();
			// 通知标题
			alert = PushModel.PASSENGER_PAY;
			// 推送内容标题
			msgTitle = PushModel.PASSENGER_PAY;
			// 推送内容
			msgContent = JSONUtil.toJSONString(pushData);
			// 设备类型
			sysType = pushPassengerPay.getLoginEquipment();

		} else if (obj instanceof PushConfirmArrival) {

			// 乘客确认到达，将Object[]转型为PushConfirmArrival
			PushConfirmArrival pushConfirmArrival = (PushConfirmArrival) obj;

			// 推送内容
			pushData.setResponseBody(pushConfirmArrival);

			// 推送Id
			registrationID = pushConfirmArrival.getDriverId();
			// 通知标题
			alert = PushModel.CONFIRM_ARRIVE;
			// 推送内容标题
			msgTitle = PushModel.CONFIRM_ARRIVE;
			// 推送内容
			msgContent = JSONUtil.toJSONString(pushData);
			// 设备类型
			sysType = pushConfirmArrival.getLoginEquipment();

		} else if (obj instanceof PushCancelOrder) {

			// 乘客确认到达，将Object[]转型为PushCancelOrder
			PushCancelOrder pushCancelOrder = (PushCancelOrder) obj;

			// 推送内容
			pushData.setResponseBody(pushCancelOrder);

			// 推送Id
			registrationID = pushCancelOrder.getDriverId();
			// 通知标题
			alert = PushModel.CANCEL_ORDER;
			// 推送内容标题
			msgTitle = PushModel.CANCEL_ORDER;
			// 推送内容
			msgContent = JSONUtil.toJSONString(pushData);
			// 设备类型
			sysType = pushCancelOrder.getLoginEquipment();

		}

		// 调用第三方发送短信平台接口
		boolean flag = SendPushUtil.sendPush(registrationID, alert, msgTitle, msgContent, sysType);

		// 打印推送失败的日志
		if (!flag && obj instanceof PushPassengerPay) {
			log.info("乘客支付成功，给司机推送消息失败");
		} else if (!flag && obj instanceof PushConfirmArrival) {
			log.info("乘客确认到达，给司机推送消息失败");
		} else if (!flag && obj instanceof PushCancelOrder) {
			log.info("乘客取消订单，给司机推送消息失败");
		}

	}

	/**
	 * @Title: getUserordert @Description: 乘客支付-验证，并返回Userordert对象 @param
	 *         reqPassengerPay 乘客支付客户端请求参数 @param dataResponse 响应对象 @author
	 *         yhq @return Userordert 返回类型 @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public Userordert getValidateAndUserordert(ReqPassengerPay reqPassengerPay, DataResponse dataResponse) {

		// 根据订单Id，查询订单信息
//		Userordert userordert = this.getUserordert(reqPassengerPay.getOid(), dataResponse);
		Userordert userordert = null;

		// 判断该订单是否为空
		if (userordert == null || userordert.getTotalMoney() == null || userordert.getOrderStatus() == null) {

			// 该订单为不存在
			setStatus(dataResponse, SystemCode.ORDER_NOT_EXIST_ERROR);
			return null;
		}

		// 判断支付宝支付金额加叮币支付金额加优惠金额是否等于乘客支付总金额
		if (reqPassengerPay.getAlipayMoney().add(reqPassengerPay.getCouponMoney()).add(reqPassengerPay.getPayMoney()) != userordert.getTotalMoney()) {

			// 支付宝支付金额加叮币支付金额加优惠金额不等于总金额
			setStatus(dataResponse, SystemCode.PASSENGER_PAY_ERROR);
			return null;
		}

		// 判断该订单的支付状态是否为待支付(乘客支付当订单状态)
		if (userordert.getOrderStatus() != ServiceCode.ORDER_STATUS_PAY) {

			// 该订单状态不为待支付
			setStatus(dataResponse, SystemCode.ORDER_NOT_PAY_STATUS_ERROR);
			return null;
		}

		// 设置支付宝付款金额
		userordert.setAlipayMoney(reqPassengerPay.getAlipayMoney());
		// 设置叮币支付金额
		userordert.setPayMoney(reqPassengerPay.getPayMoney());
		// 设置优惠金额
		userordert.setCouponMoney(reqPassengerPay.getCouponMoney());

		return userordert;
	}

	/**
	 * @Title: validateOrderInfo @Description: 乘客支付-验证，并返回Userordert对象 @param
	 *         reqPassengerPay 乘客支付客户端请求参数 @param dataResponse 响应对象 @author
	 *         yhq @return Userordert 返回类型 @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public Userordert validateOrderInfo(ReqPayOrder reqPayOrder, DataResponse dataResponse) {

		// 根据订单Id，查询订单信息
//		Userordert userordert = this.getUserordert(reqPayOrder.getOid(), dataResponse);
		Userordert userordert = null;

		// 根据用户Id获取用户账户信息
		Useraccount useraccount = this.getUserAccount(reqPayOrder.getPassengerID(), dataResponse);

		// 判断该订单是否为空
		if (userordert == null || userordert.getTotalMoney() == null || userordert.getOrderStatus() == null
				|| useraccount == null || useraccount.getCurrencyAmount() == null) {

			// 该订单为不存在
			setStatus(dataResponse, SystemCode.ORDER_NOT_EXIST_ERROR);
			return null;
		}

		// 账户余额取整
		BigDecimal currentAmount = useraccount.getCurrencyAmount();

		if (reqPayOrder.getPayType() == 3) { // 叮币支付

			if (userordert.getTotalMoney() != reqPayOrder.getPayMoney().add(reqPayOrder.getCouponMoney())) {
				// 支付宝支付金额加叮币支付金额加优惠金额不等于总金额
				setStatus(dataResponse, SystemCode.PASSENGER_PAY_ERROR);
				return null;
			} else if (currentAmount.compareTo(reqPayOrder.getPayMoney()) < 0) {
				// 支付宝支付金额加叮币支付金额加优惠金额不等于总金额
				setStatus(dataResponse, SystemCode.BALANCE_NOT_ENOUGH_ERROR);
				return null;
			}

		} else { // 第三方支付

			// 判断优惠券金额是否金额
			BigDecimal couponMoney = userordert.getCouponMoney();

			if (couponMoney == null) {
				couponMoney = new BigDecimal(0);
			}

			// 判断该订单的支付状态是否为待支付(乘客支付当订单状态)
			if (userordert.getOrderStatus() != ServiceCode.ORDER_STATUS_PAY) {

				// 该订单状态不为待支付
				setStatus(dataResponse, SystemCode.ORDER_NOT_PAY_STATUS_ERROR);
				return null;
			}

			// 服务器计算的第三方支付金额
			BigDecimal payMoney = userordert.getTotalMoney().subtract(couponMoney).subtract(currentAmount);

			if (!payMoney.equals(reqPayOrder.getAlipayMoney())) {
				// 支付宝支付金额加叮币支付金额加优惠金额不等于总金额
				setStatus(dataResponse, SystemCode.PASSENGER_PAY_ERROR);
				return null;
			}

		}

		// 设置支付宝付款金额
		userordert.setAlipayMoney(reqPayOrder.getAlipayMoney());
		// 设置叮币支付金额
		userordert.setPayMoney(reqPayOrder.getPayMoney());
		// 设置优惠金额
		userordert.setCouponMoney(reqPayOrder.getCouponMoney());
		// 设置支付类型
		if (reqPayOrder.getPayType() != null) {
			userordert.setPayType(reqPayOrder.getPayType());
		}

		return userordert;
	}

	/**
	 * @Title: passengerDebit @Description: 乘客扣款 @param oid 订单Id @return
	 *         PushCompetitiveOrder 返回类型 @author yhq @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public PushCompetitiveOrder passengerDebit(Userordert userordert, PushCompetitiveOrder pushCompetitiveOrder,
			DataResponse dataResponse) {

		// 判断该订单信息是否存在
		if (userordert == null || userordert.getOrderType() == null
				|| ToolUtil.isBlank(userordert.getPlaceOrderUserId())
				|| ToolUtil.isBlank(userordert.getGrabOrderUserId())) {
			// 订单信息不存在
			setStatus(dataResponse, SystemCode.ORDER_NOT_EXIST_ERROR);
			return null;
		}

		// 乘客Id
		String passengerId = null;

		/**
		 * 获取乘客Id 1.订单为乘客下单时，判断如果当前用户等于下单用户，则该订单的抢单用户为司机角色
		 * 2.订单为司机下单时，判读如果当前用户等于抢单用户，则该订单的抢单用户为司机角色 3.否则其他情况则为下单用户为司机。
		 */
		if (userordert.getOrderType() == ServiceCode.PASSENGER_PLACE_AN_ORDER) {
			passengerId = userordert.getPlaceOrderUserId();
		} else if (userordert.getOrderType() == ServiceCode.DRIVER_PLACE_AN_ORDER) {
			passengerId = userordert.getGrabOrderUserId();
		}

		// 判断乘客Id是否已存在
		if (passengerId == null) {
			// 乘客支付时，乘客Id为空
			setStatus(dataResponse, SystemCode.ORDER_INFO_IS_NULL_ERROR);
			return null;
		}

		// 获取下单用户电话以及推送内容
		pushCompetitiveOrder = super.userDetailDao.getUserInfo(userordert.getOrderType(),
				userordert.getPlaceOrderUserId(), userordert.getGrabOrderUserId());

		// 根据乘客Id查询乘客的账户信息
		Useraccount useraccount = super.userAccountService.getUserAccountByUserId(passengerId, dataResponse);
		// 判断该乘客账户信息是否存在
		if (useraccount == null || useraccount.getCurrencyAmount() == null) {
			return null;
		}

		// 账户余额不够
		if (useraccount.getCurrencyAmount().compareTo(userordert.getPayMoney()) < 0) {

			setStatus(dataResponse, SystemCode.BALANCE_NOT_ENOUGH_ERROR);
			return null;
		}

		// 扣除乘客应支付叮币
		useraccount.setCurrencyAmount(useraccount.getCurrencyAmount().subtract(userordert.getPayMoney()));

		// 支付时间
		userordert.setPayTime(new Date());
		// 订单状态(3:已支付)
		userordert.setOrderStatus(ServiceCode.ORDER_STATUS_PAID);

		try {
			super.userOrderTDao.update(userordert);
		} catch (Exception e) {
			log.error("修改订单状态时出现异常   类：" + this.getClass() + " passengerDebit()", e);
		}

		// 更改缓存中订单状态
//		OrderCache orderCache = new OrderCache();
		// 设置缓存中订单状态为已支付
//		boolean isUpdateSucc = orderCache.setOrderStatus(userordert.getOid(), "3");
//		if (!isUpdateSucc) {
//			log.error("更改缓存订单状态为已支付出现错误！订单编号为：" + userordert.getOid());
//		}

		return pushCompetitiveOrder;
	}

	/**
	 * @Title: getUserorder @Description: 将UserOrdert中的数据赋值给UserOrder @param
	 *         userOrdert 订单临时表对象中的数据 @author yhq @return UserOrder
	 *         订单正式表对象 @throws
	 */
	public Userorder getUserorder(Userordert userordert) {

		// 创建userOrder对象
		Userorder userOrder = new Userorder();
		// 主键Id
		userOrder.setOid(userordert.getOid());
		// 下单用户Id
		userOrder.setPlaceOrderUserId(userordert.getPlaceOrderUserId());
		// 下单城市
		userOrder.setPayCity(userordert.getPayCity());
		// 出发时间
		userOrder.setSetOutTime(userordert.getSetOutTime());
		// 出发地址
		userOrder.setStartAddress(userordert.getStartAddress());
		// 起点经度
		userOrder.setStartLongitude(userordert.getStartLongitude());
		// 起点纬度
		userOrder.setStartLatitude(userordert.getStartLatitude());
		// 目的地
		userOrder.setEndAddress(userordert.getEndAddress());
		// 目的地经度
		userOrder.setEndLongitude(userordert.getEndLongitude());
		// 目的地纬度
		userOrder.setEndLatitude(userordert.getEndLatitude());
		// 距离
		userOrder.setDistance(userordert.getDistance());
		// 叮币支付金额
		userOrder.setPayMoney(userordert.getPayMoney());
		// 支付宝支付金额
		userOrder.setAlipayMoney(userordert.getAlipayMoney());
		// 总金额
		userOrder.setTotalMoney(userordert.getTotalMoney());
		// 人数
		userOrder.setNumber(userordert.getNumber());
		// 红包
		userOrder.setRedBag(userordert.getRedBag());
		// 留言
		userOrder.setMessage(userordert.getMessage());
		// 距对方距离
		userOrder.setPayDistance(userordert.getPayDistance());
		// 标志建筑物
		userOrder.setMarker(userordert.getMarker());
		// 抢单用户Id
		userOrder.setGrabOrderUserId(userordert.getGrabOrderUserId());
		// 抢单时间
		userOrder.setGrabOrderTime(userordert.getGrabOrderTime());
		// 订单状态
		userOrder.setOrderStatus(userordert.getOrderStatus());
		// 下单时间
		userOrder.setCreateTime(userordert.getCreateTime());
		// 订单支付时间
		userOrder.setPayTime(userordert.getPayTime());
		// 乘客确认到达时间
		userOrder.setEndTime(userordert.getEndTime());
		// 取消订单时间
		userOrder.setCancelTime(null);
		// 下单用户类型
		userOrder.setOrderType(userordert.getOrderType());
		// 取消类型
		userOrder.setCancelType(userordert.getCancelType());
		// 订单取消原因
		userOrder.setCancelDesc(userordert.getCancelDesc());
		// 1:普通 2:长途
		userOrder.setIsLongDistance(userordert.getIsLongDistance());
		// 用户优惠券Id
		userOrder.setUcId(userordert.getUcId());
		// 优惠金额
		userOrder.setCouponMoney(userordert.getCouponMoney());
		// 支付类型
		userOrder.setPayType(userordert.getPayType());

		return userOrder;
	}

	/**
	 * 
	 * @Title: setStatus @Description:根据状态码设置响应信息 @param dataResponse
	 *         响应信息封装bean @param status 状态码 @author yHQ @return void @throws
	 */
	@Override
	public void setStatus(DataResponse dataResponse, int status) {
		String message = null;
		switch (status) {
		case SystemCode.DATA_NULL_ERROR:// 传入参数为空
			message = SystemCode.DATA_NULL_MESSAGE;
			break;
		case SystemCode.ORDER_NOT_EXIST_ERROR:// 订单不存在
			message = SystemCode.ORDER_NOT_EXIST_MESSAGE;
			break;
		case SystemCode.PASSENGER_COMPLETE_ORDER_ERROR:// 订单已完成
			message = SystemCode.PASSENGER_COMPLETE_ORDER_MESSAGE;
			break;
		case SystemCode.PASSENGER_CANCEL_ORDER_ERROR:// 订单已取消
			message = SystemCode.PASSENGER_CANCEL_ORDER_MESSAGE;
			break;
		case SystemCode.NOT_ALREADY_PAY_ERROR: // 该订单状态不是已支付状态
			message = SystemCode.NOT_ALREADY_PAY_MESSAGE;
			break;
		case SystemCode.NOT_EXIST_ACCOUNT_INFO_ERROR:// 该用户不存在账户信息
			message = SystemCode.NOT_EXIST_ACCOUNT_INFO_MESSAGE;
			break;
		case SystemCode.ORDER_NOT_PAY_STATUS_ERROR:// 该订单不是待支付状态
			message = SystemCode.ORDER_NOT_PAY_STATUS_MESSAGE;
			break;
		case SystemCode.ORDER_INFO_IS_NULL_ERROR:// 乘客支付时，乘客Id为空
			message = SystemCode.ORDER_INFO_IS_NULL_MESSAGE;
			break;
		case SystemCode.PASSENGER_PAY_ERROR:// 支付宝支付金额加叮币支付金额不等于总金额
			message = SystemCode.PASSENGER_PAY_MESSAGE;
			break;
		case SystemCode.TRANSFER_ACCOUNTS_FAILURE_ERROR:// 用户转账失败
			message = SystemCode.TRANSFER_ACCOUNTS_FAILURE_MESSAGE;
			break;
		case SystemCode.SUCCESS:// 请求成功
			message = SystemCode.SUCCESS_MESSAGE;
			break;
		case SystemCode.ERROR:// 系统异常
			message = SystemCode.ERROR_MESSAGE;
			break;
		case SystemCode.BALANCE_NOT_ENOUGH_ERROR:
			message = SystemCode.BALANCE_NOT_ENOUGH_MESSAGE;
			break;
		}

		dataResponse.setResponseCode(status);
		dataResponse.setResponseMessage(message);
	}

	/**
	 * @Title: getUserordert @Description: 根据订单Id获取订单信息 @param oId @return
	 *         UserOrdert 返回类型 @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public Userordert getUserordert(String oid, DataResponse dataResponse) {

		// 添加订单Id作为查询条件
		Criterion criterion = Restrictions.eq("oid", oid);

		// 根据订单Id查询订单信息
		Userordert userordert = null;

		try {
			userordert = super.userOrderTDao.queryCriteriaUnResult(criterion, false);
		} catch (Exception e) {
			log.error("根据订单Id获取订单信息时出现异常  类：" + this.getClass() + " getUserordert()", e);
			setStatus(dataResponse, SystemCode.ERROR);
		}

		return userordert;
	}

	/**
	 * @Title: getUserAccount
	 * @Description: 根据用户Id获取用户账户信息
	 * @param loginId
	 *            用户Id
	 * @author YHQ
	 * @return Useraccount 返回类型
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public Useraccount getUserAccount(String loginId, DataResponse dataResponse) {

		// 添加订单Id作为查询条件
		Criterion criterion = Restrictions.eq("loginId", loginId);

		// 根据订单Id查询订单信息
		Useraccount useraccount = null;

		try {
			useraccount = super.userAccountDao.queryCriteriaUnResult(criterion, false);
		} catch (Exception e) {
			log.error("根据订单Id获取订单信息时出现异常  类：" + this.getClass() + " getUserordert()", e);
			setStatus(dataResponse, SystemCode.ERROR);
		}

		return useraccount;
	}

	/**
	 * @Title: LatelyOrder @Description: 查看用户最近订单 @param reqPassengerPay
	 *         查看用户最近订单客户端请求参数 @param dataResponse 响应Bean @author yhq @return
	 *         void 返回类型 @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void latelyOrder(ReqGetLastUserOrder reqGetLastUserOrder, DataResponse dataResponse) {

		// 验证客户端传入的参数是否为空
		if (reqGetLastUserOrder == null || ToolUtil.isBlank(reqGetLastUserOrder.getUserId())) {
			setStatus(dataResponse, SystemCode.DATA_NULL_ERROR);
			return;
		}

		// 获取未完成的订单
		Object object = super.userOrderTDao.latelyOrder(dataResponse, reqGetLastUserOrder);

		// 创建响应Bean对象
		List<ResGetLastUserOrder> resGetLastUserOrder = null;

		if (object instanceof Integer && object.equals(0)) {
			// 异常
			setStatus(dataResponse, SystemCode.ERROR);
			return;
		} else if (object instanceof Integer && object.equals(1)) {
			// 无数据
			setStatus(dataResponse, SystemCode.SUCCESS);
			return;
		}
		// 有数据
		resGetLastUserOrder = (List<ResGetLastUserOrder>) object;
		// resGetLastUserOrder.setCurrentSerTime(new Date());
		// 响应内容
		dataResponse.setResponseBody(resGetLastUserOrder);
		// 响应码
		setStatus(dataResponse, SystemCode.SUCCESS);

	}

	/**
	 * @Title: getUserOrder @Description: 我的订单 @param reqGetUserOrder
	 *         我的订单-客户端请求Bean @author yhq @return void 返回类型 @throws
	 */
	@Override
	@Transactional(readOnly = true)
	public void getUserOrder(ReqGetUserOrder reqGetUserOrder, DataResponse dataResponse) {

		// 验证我的订单传入的参数是否为空
		boolean flag = this.validateGetUserOrder(reqGetUserOrder);

		if (!flag) {
			setStatus(dataResponse, SystemCode.DATA_NULL_ERROR);
			return;
		}

		// 获取我的订单列表
		Object object = super.userOrderTDao.getUserOrder(dataResponse, reqGetUserOrder);

		// 创建查询我的订单响应Bean
		ResGetUserOrder resGetUserOrder = new ResGetUserOrder();

		if (object instanceof Integer && object.equals(0)) {
			// 异常
			setStatus(dataResponse, SystemCode.ERROR);
			return;
		} else if (object instanceof Integer && object.equals(1)) {
			// 暂不处理
		} else {
			// 有数据
			resGetUserOrder = (ResGetUserOrder) object;
		}

		// 获取当前用户的接乘里程和搭乘里程
		// 将用户Id作为查询条件
		Criterion criterion = Restrictions.eq("loginId", reqGetUserOrder.getUserId());
		// 根据用户Id获取其接乘里程和搭乘里程
		Userdetail userdetail = null;
		try {
			userdetail = super.userDetailDao.queryCriteriaUnResult(criterion, false);
		} catch (Exception e) {
			log.error("获取用户详情时出现异常  类：" + this.getClass() + " 方法：getUserOrder()", e);
			setStatus(dataResponse, SystemCode.ERROR);
			return;
		}

		// 用户不存在
		if (userdetail == null || userdetail.getTotalWeldingProcess() == null || userdetail.getTotalTake() == null) {
			setStatus(dataResponse, SystemCode.USER_INFO_NOT_EXIST_ERROR);
			return;
		}

		if (userdetail.getTotalWeldingProcess() != null) {
			// 总接乘
			resGetUserOrder.setPickUpMeters(userdetail.getTotalWeldingProcess());
		} else {
			resGetUserOrder.setPickUpMeters(new BigDecimal(0));
		}

		if (userdetail.getTotalTake() != null) {
			// 总搭乘
			resGetUserOrder.setRideMeters(userdetail.getTotalTake());
		} else {
			resGetUserOrder.setRideMeters(new BigDecimal(0));
		}

		// 返回响应参数
		dataResponse.setResponseBody(resGetUserOrder);
		// 返回响应码
		setStatus(dataResponse, SystemCode.SUCCESS);

	}

	/**
	 * @Title: validateGetUserOrder @Description: 验证获取我的订单时客户端传入参数是否为空 @param
	 *         reqGetUserOrder 客户端传入参数 @return true 参数正确 false 参数有误 @throws
	 */
	public boolean validateGetUserOrder(ReqGetUserOrder reqGetUserOrder) {

		if (reqGetUserOrder == null // 客户端传入参数
				|| ToolUtil.isBlank(reqGetUserOrder.getUserId()) // 用户Id是否为空
				|| reqGetUserOrder.getOrderStatus() == null // 订单类型是否为空 4:已完成
															// 5:已取消
				|| reqGetUserOrder.getPageIndex() == null // 当前页是否为空
				|| reqGetUserOrder.getPageSize() == null) { // 每页显示记录数是否为空

			return false;
		}

		return true;
	}

	/**
	 * @Title: automaticConfirmArrival @Description: 两个小时后自动确认到达 @return void
	 *         返回类型 @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = RuntimeException.class)
	public void automaticConfirmArrival() {

		// 获取待确认到达订单列表
		List<PushAutomaticCancelOrder> list = super.userOrderTDao.getConfirmOrders();

		// 判断待完成订单列表是否为空
		if (list != null && list.size() > 0) {

			log.info("存在符合自动确认到达条件的订单");
			for (PushAutomaticCancelOrder pushAutomaticCancelOrder : list) {
				// 执行确认到达操作
				this.confirmArrivalOperation(pushAutomaticCancelOrder);
			}
		}

	}

	/**
	 * @Title: batchConfirmArrival @Description: 批量处理待确认到达订单 @return boolean
	 *         返回类型 @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean batchConfirmArrival() {

		try {
			// 批量处理待确认到达订单(将待确认到达的订单转存入userOrder表中)
			super.userOrderDao.addNativeSQLRow(UserOrderDaoSql.BATCH_HANDLE_CONFIRM_ARRIVAL);
		} catch (Exception e) {
			log.error("批量处理待确认到达订单时出现异常   类：" + this.getClass() + " batchConfirmArrival()", e);
			return false;
		}

		return true;
	}

	/**
	 * @Title: batchDeleteConfirmArrival @Description:
	 *         批量删除userOrdert表中的待确认到达 @param @return 设定文件 @return boolean
	 *         返回类型 @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean batchDeleteConfirmArrival() {

		try {
			// 批量删除userOrdert表中的待确认到达数据
			super.userOrderDao.updateSqlRow(UserOrderDaoSql.BATCH_DELETE_CONFIRM_ARRIVAL);
		} catch (Exception e) {
			log.error("批量删除userOrdert表中的待确认到达时出现异常  类：" + this.getClass() + " batchDeleteConfirmArrival()", e);
			return false;
		}
		return true;
	}

	/**
	 * 自动确认到达操作
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void confirmArrivalOperation(PushAutomaticCancelOrder pushAutomaticCancelOrder) {

		// 给司机转账,并添加一条交易明细
		boolean transferAccounts = this.transferAccountsToDriver(pushAutomaticCancelOrder);

		// 判断给司机转账是否成功
		if (!transferAccounts) {
			return;
		}

		// 判断当前环境是正式环境还是测试环境(测试环境的话接单次数不需要增加)
		if (environmentParam) {
			// 给司机和乘客双方都要增加一个接单次数
			boolean flag = this.addReachOrderNumber(pushAutomaticCancelOrder);

			// 判断司机或乘客是否增加成功
			if (!flag) {
				return;
			}
		}

		// 创建司机查询条件
		Criterion criterionDriver = Restrictions.eq("loginId", pushAutomaticCancelOrder.getDriverId());
		// 创建乘客查询条件
		Criterion criterionPassenger = Restrictions.eq("loginId", pushAutomaticCancelOrder.getPassengerId());
		// 给司机和乘客累计搭乘和接乘次数和里程

		// 获取司机的用户详情
		Userdetail userdetailDriver = null;
		// 获取乘客的用户详情
		Userdetail userdetailPassenger = null;
		try {
			userdetailDriver = super.userDetailDao.queryCriteriaUnResult(criterionDriver, false);

			userdetailPassenger = super.userDetailDao.queryCriteriaUnResult(criterionPassenger, false);
		} catch (Exception e) {
			log.info("获取司机或乘客的用户详情是出现异常   类：" + this.getClass() + " confirmArrivalOperation()", e);
		}

		// 判断司机和乘客的用户详情是否为空
		if (userdetailDriver == null || userdetailPassenger == null) {
			return;
		}

		// 司机总接乘里程累加
		userdetailDriver.setTotalWeldingProcess(
				userdetailDriver.getTotalWeldingProcess().add(pushAutomaticCancelOrder.getDistance()));
		// 司机的总接乘次数加一
		userdetailDriver.setTotalWeldingProcessNumber(userdetailDriver.getTotalWeldingProcessNumber() + 1);
		// 乘客总搭乘里程累加
		userdetailPassenger.setTotalTake(userdetailPassenger.getTotalTake().add(pushAutomaticCancelOrder.getDistance()));
		// 乘客的总搭乘次数加一
		userdetailPassenger.setTotalTakeNumber(userdetailPassenger.getTotalTakeNumber() + 1);

		// 参加活动,类型为自动完成订单
		BigDecimal integral = activityService.attendActivity(pushAutomaticCancelOrder.getDriverId(),
				AttendActivityEnum.COMPLETE_ORDER);
		pushAutomaticCancelOrder.setIntegral(integral);

		if (integral.compareTo(new BigDecimal(0)) != 0) {
			// 将参加活动所赠积分添加到订单表中
			boolean status = userOrderTDao.updateCurrentOrderReceiveIntegral(integral,pushAutomaticCancelOrder.getOid());
		}

		// 给司机和乘客发送短信、推送消息
		this.sendMessageByConfirmArrival(pushAutomaticCancelOrder);

	}

	/**
	 * 自动确认到达-给司机转账
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = RuntimeException.class)
	public boolean transferAccountsToDriver(PushAutomaticCancelOrder pushAutomaticCancelOrder) {

		String passengerId = pushAutomaticCancelOrder.getPassengerId();// 乘客Id
		String driverId = pushAutomaticCancelOrder.getDriverId();// 司机Id
		BigDecimal totalMoney = pushAutomaticCancelOrder.getTotalMoney();// 总金额
		BigDecimal distance = pushAutomaticCancelOrder.getDistance();// 总里程

		// 获取司机账户
		Criterion criterion = Restrictions.eq("loginId", driverId);
		// 获取乘客账户
		Criterion passengerCondition = Restrictions.eq("loginId", passengerId);

		// 司机账户
		Useraccount useraccount = null;
		// 乘客账户
		Useraccount useraccount2 = null;

		try {
			// 获取用户账户信息
			useraccount = super.userAccountDao.queryCriteriaUnResult(criterion, false);
			useraccount2 = super.userAccountDao.queryCriteriaUnResult(passengerCondition, false);
		} catch (Exception e) {
			log.error("自动确认到达时给司机转账时出现异常", e);
			return false;
		}

		if (useraccount == null || useraccount2 == null) {
			return false;
		}

		// 给司机增加钱
		useraccount.setCurrencyAmount(useraccount.getCurrencyAmount().add(totalMoney));

		// 司机累计收入
		useraccount.setTotalIncome(useraccount.getTotalIncome().add(totalMoney));

		// 乘客增加累计支出
		useraccount2.setTotalExpend(useraccount2.getTotalExpend().add(totalMoney));

		Userordert userordert = new Userordert();

		// 总金额
		userordert.setTotalMoney(pushAutomaticCancelOrder.getTotalMoney());
		// 支付宝支付金额
		userordert.setAlipayMoney(pushAutomaticCancelOrder.getAlipayMoney());
		// 叮币支付金额
		userordert.setPayMoney(pushAutomaticCancelOrder.getPayMoney());
		// 优惠金额
		userordert.setCouponMoney(pushAutomaticCancelOrder.getCouponMoney());

		// 添加交易明细
		boolean isSuccess = this.addUserAccountDetail(passengerId, driverId, userordert);

		return isSuccess;
	}

	/**
	 * @Title: sendMessageByConfirmArrival @Description: 自动确认到达-发送短信、推送消息 @param
	 *         userordert @author yhq @return void @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean sendMessageByConfirmArrival(PushAutomaticCancelOrder pushAutomaticCancelOrder) {

		// 给乘客发送短信，推送消息
		if (ToolUtil.isNotBlank(pushAutomaticCancelOrder.getPassengerId())) {
			//将消息加到消息队列
			MessageRequestsDTO messageRequestsDTO = new MessageRequestsDTO();
			messageRequestsDTO.setTelPhone(pushAutomaticCancelOrder.getPassengerPhone());
			messageRequestsDTO.setMessageContent(MessageModel.AUTO_CONFIRM_ARRIVAL);
			queuefacade.addMessageToQueue(JSONUtil.toJSONString(messageRequestsDTO));
			// 推送Bean
			PushData pushData = new PushData();

			// 推送序号(时间戳)
			pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
			// 推送时间
			pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
			// 模块
			pushData.setModular(ServiceCode.CONFIRM_ARRIVAL);
			// 推送内容
			pushData.setResponseBody(pushAutomaticCancelOrder);
			// 给乘客推送消息

			SendPushUtil.sendPush(pushAutomaticCancelOrder.getPassengerAliasId(), PushModel.AUTO_CONFIRM_ARRIVAL,
					PushModel.AUTO_CONFIRM_ARRIVAL, JSONUtil.toJSONString(pushData),
					pushAutomaticCancelOrder.getPassengerEquipment());

		}

		// 给司机发送短信，推送消息
		if (ToolUtil.isNotBlank(pushAutomaticCancelOrder.getDriverId())) {

			// 给司机发送短信
			MessageRequestsDTO messageRequestsDTO = new MessageRequestsDTO();
			messageRequestsDTO.setTelPhone(pushAutomaticCancelOrder.getDriverPhone());
			messageRequestsDTO.setMessageContent(
					MessageModel.confirmArrive(pushAutomaticCancelOrder.getDriverName(), pushAutomaticCancelOrder.getIntegral()));
			queuefacade.addMessageToQueue(JSONUtil.toJSONString(messageRequestsDTO));
			// 推送Bean
			PushData pushData = new PushData();

			// 推送序号(时间戳)
			pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
			// 推送时间
			pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
			// 模块
			pushData.setModular(ServiceCode.CONFIRM_ARRIVAL);
			// 推送内容
			pushData.setResponseBody(pushAutomaticCancelOrder);

			// 给司机推送消息
			SendPushUtil.sendPush(pushAutomaticCancelOrder.getDriverAliasId(), PushModel.CONFIRM_ARRIVE,
					PushModel.CONFIRM_ARRIVE, JSONUtil.toJSONString(pushData),
					pushAutomaticCancelOrder.getDriverEquipment());

		}

		return true;

	}

	/**
	 * @Title: getAllUserOrder @Description: 获取订单表中的全部数据(数据迁移专用) @return
	 *         List<Userorder> 返回类型 @throws
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Userorder> getAllUserOrder() {

		return super.userOrderDao.queryAll(false);
	}

	/**
	 * @Title: updateAllOid @Description:
	 *         修改订单Id(将订单Id改为时间戳加六位随机数)(数据迁移专用) @return boolean 返回类型 @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean updateAllOid(List<Userorder> userorders) {

		// 判断返回订单列表是否为空
		if (userorders != null && userorders.size() > 0) {

			for (Userorder userorder : userorders) {

				// 产生一个订单Id
				String oid = ToolUtil.getUid();

				userorder.setOid(oid);

				try {
					super.userOrderDao.save(userorder);
					Thread.sleep(1);
				} catch (Exception e) {
					log.info("修改订单Id是出现异常   类：" + this.getClass() + " updateAllOid()", e);
					return false;
				}

			}

			return true;

		}

		return false;
	}

	/**
	 * @Title: deleteAllOid @Description: 删除集合中的全部数据(数据迁移专用) @return boolean
	 *         返回类型 @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean deleteAllOid() {

		// 全部订单
		int row = 0;
		try {
			row = super.userOrderDao.updateSqlRow("DELETE FROM userorder");
		} catch (Exception e) {
			log.info("删除全部的订单信息时出现异常  ,类：" + this.getClass() + " deleteAllOid()", e);
			return false;
		}

		// 判断删除订单是否成功
		if (row > 0) {
			return true;
		}

		return false;
	}

	/**
	 * @Title: verifyWechatPayResult @Description: 根据微信返回的结果验证支付结果 @param
	 *         wechatPayResult 微信服务器返回给我们的用户支付结果 @author fengshuonan @return
	 *         boolean true 验证成功 false 验证失败 @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean verifyWechatPayResult(WechatPayResult wechatPayResult) {

		// 如果微信返回的信息不为空 并且消息code为SUCCESS
		if (wechatPayResult != null && "SUCCESS".equals(wechatPayResult.getReturn_code())
				&& "SUCCESS".equals(wechatPayResult.getResult_code())) {

			// 根据订单Id获取订单信息
			Userordert userordert = getUserordert(wechatPayResult.getOut_trade_no(), new DataResponse());

			// 如果没有订单信息
			if (userordert == null) {
				log.error("根据微信回调返回的订单信息为空！  订单Id:"+wechatPayResult.getOut_trade_no() + "  类："+this.getClass()+" line: 2134");
				return false;
			}

			// 执行乘客扣款，并返回推送内容
			PushCompetitiveOrder pushCompetitiveOrder = super.userOrderService.passengerDebit(userordert, null,
					new DataResponse());

			if (pushCompetitiveOrder != null) {
				String passengerId = null;// 乘客Id
				String driverId = null;// 司机Id

				// 如果为乘客下单
				if (userordert.getOrderType() == 2) {
					passengerId = userordert.getPlaceOrderUserId();
					driverId = userordert.getGrabOrderUserId();
				} else if (userordert.getOrderType() == 1) {

					// 如果为司机下单，分别获取乘客司机
					passengerId = userordert.getGrabOrderUserId();
					driverId = userordert.getPlaceOrderUserId();
				}

				// 发送短信以及推送消息
				super.userOrderService.passengerPaySendInfo(passengerId, driverId, userordert);
			}

			return true;
		} else {

			// 如果微信返回的信息为空或者微信返回的code为FAIL
			return false;
		}
	}

	/**
	 * @Title: queryOrderResult
	 * @Description: 订单结果查询
	 * @author fengshuonan
	 * @return void
	 * @Override
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void queryOrderResult(ReqQueryOrderResult reqWePayOrderQuery, DataResponse dataResponse) {

		// 返回客户端支付结果
		ResQueryOrderResult resWePayOrderQuery = new ResQueryOrderResult();

		// 验证请求数据是否为空
		if (reqWePayOrderQuery == null || ToolUtil.isBlank(reqWePayOrderQuery.getOid())) {
			dataResponse.setResponseCode(SystemCode.DATA_NULL_ERROR);
			dataResponse.setResponseMessage(SystemCode.DATA_NULL_MESSAGE);
			return;
		}

		/**
		 * 获取订单的状态
		 *
		 * 修改人：冯硕楠 
		 * 修改原因：订单业务新增出租车订单，所以要加上出租车订单状态的判断 
		 * 修改时间：2016年7月6日19:00:04
		 * 修改版本：V2.3
		 */
		Integer normalOrderStatus = null;
		Integer taxiOrderStatus = null;

		//先获取合乘订单的订单状态
		normalOrderStatus = super.userOrderFacade.getUserOrderStatus(reqWePayOrderQuery.getOid());
		
		if(normalOrderStatus == null || normalOrderStatus == 0){
			taxiOrderStatus = super.userOrderFacade.getTaxiUserOrderStatus(reqWePayOrderQuery.getOid());
		}

		// 如果订单状态为已支付,返回订单支付成功
		if ( (normalOrderStatus != null && normalOrderStatus == ServiceCode.ORDER_STATUS_PAID) || 
				(taxiOrderStatus != null && taxiOrderStatus == 4) ) {
			resWePayOrderQuery.setOrderStatus(ServiceCode.ORDER_RESULT_SUCCESS);
			dataResponse.setResponseBody(resWePayOrderQuery);
			setStatus(dataResponse, SystemCode.SUCCESS);
			return;
		}

		/**
		 * 根据订单状态判断订单是否已完成支付 如果是待支付状态，则发送微信api请求确认是否未支付，如果已支付直接返回给前台已支付
		 */
		if ( (normalOrderStatus != null && normalOrderStatus == ServiceCode.ORDER_STATUS_PAY) || 
				(taxiOrderStatus != null && taxiOrderStatus == 3) ) {// 如果是待支付
			// 调用api向微信发送请求，查看订单是否完成
			WechatPayApi api = new WechatPayApi();
			WechatPayOrderQueryResponse response = api
					.orderQuery(WechatPayApi.createWechatPayQueryRequest(reqWePayOrderQuery.getOid()));

			// 如果微信返回的返回状态码和业务结果 都为“成功”
			if (response != null
					&& ("SUCCESS".equals(response.getReturn_code()) && "SUCCESS".equals(response.getResult_code()))) {

				// 如果微信服务器返回该订单已支付
				if ("SUCCESS".equals(response.getTrade_state())) {

					// 改变订单状态为已支付
					super.userOrderTService.setOrderStatus(reqWePayOrderQuery.getOid(), ServiceCode.ORDER_STATUS_PAID);

					// 返回订单支付成功
					resWePayOrderQuery.setOrderStatus(ServiceCode.ORDER_RESULT_SUCCESS);
				}
			} else {

				log.error("从微信服务器查询该订单出错！UserOrderServiceImpl:queryOrderResult()" + response.getErr_code() + ","
						+ response.getErr_code_des());
				resWePayOrderQuery.setOrderStatus(ServiceCode.ORDER_RESULT_FAIL);// 返回订单支付失败
			}

			// 返回服务器响应状态码
			dataResponse.setResponseBody(resWePayOrderQuery);
			setStatus(dataResponse, SystemCode.SUCCESS);
			return;

		} else {

			// 如果查询到当前状态为其他状态（不是已支付或待支付）
			setStatus(dataResponse, SystemCode.ERROR);
			return;
		}
	}

}
